package com.anti_poverty_detection_system.springboot.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 *  令牌工具类
 * </p>
 *
 * @author ZITONG BAI
 * @since 2024-06-17
 */
@Component
public class JwtUtils {

    // 令牌密钥
    @Value("${jwt.secret}")
    private String secret;
    // 令牌过期时间
    @Value("${jwt.expiration}")
    private Long expiration;
    // 刷新令牌过期时间
    @Value("${jwt.refreshExpiration}")
    private Long refreshExpiration;

    // 生成令牌
    public String generateToken(String username) throws UnsupportedEncodingException {
        Date nowDate = new Date();
        // 过期时间
        Date expireDate = new Date(nowDate.getTime() + expiration * 1000);

        return JWT.create()
                .withClaim("username", username)
                .withIssuedAt(nowDate)
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(secret));
    }

    // 刷新令牌
    public String refreshToken(String token) throws UnsupportedEncodingException {
        DecodedJWT jwt = JWT.decode(token);
        Date nowDate = new Date();
        // 刷新后过期时间
        Date expireDate = new Date(nowDate.getTime() + refreshExpiration * 1000);
        return JWT.create()
                .withClaim("username", jwt.getClaim("username").asString())
                .withIssuedAt(nowDate)
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(secret));

    }

    // 验证令牌
    public boolean verifyToken(String token){
        try {
            JWTVerifier jwtVerifier= null;
            try {
                jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            jwtVerifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }

    // 从令牌中获取用户名
    public String getUsernameFromToken(String token){
        DecodedJWT jwt=JWT.decode(token);
        return jwt.getClaim("username").asString();
    }
}
